package com.example.myapplication.ui.activity.square

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView
import com.example.myapplication.R
import com.example.myapplication.arouter.ARouterPath
import com.example.myapplication.bean.article.ArticleBean
import com.example.myapplication.bean.square.UserSharedBean
import com.example.myapplication.dialog.OperationDialog
import com.example.myapplication.ui.adapter.ArticleAdapter
import com.kun.base.env.Constants
import com.kun.base.env.Env
import com.kun.base.net.ResponseResult
import com.kun.base.ui.AbsBaseActivity
import com.kun.base.util.MMKVUtils
import com.scwang.smart.refresh.header.ClassicsHeader
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.list_user_shared_header.*
import kotlinx.android.synthetic.main.toolbar_layout.*

/**
 *我分享的
 * 参数（
 *  userId  [Int] 用户id ,不传为自己；
 *  nickName [String] 用户昵称，不传为自己
 * ）
 * @author : Kun
 * @date : 2021/6/10
 * @time : 10:35
 */
@Route(path = ARouterPath.USER_SHARED)
class UserSharedActivity : AbsBaseActivity() {
    private lateinit var tvUserName: TextView
    private lateinit var tvCoins: TextView
    private lateinit var tvLevel: TextView

    private var index = 1
    private lateinit var articleAdapter: ArticleAdapter

    /**
     * 用户id，空为自己
     */
    @JvmField
    @Autowired
    var userId: Int = 0

    /**
     * 用户昵称，空为自己
     */
    @JvmField
    @Autowired
    var nickName: String = ""

    private lateinit var userSharedViewModel: UserSharedViewModel

    override fun getLayoutId(): Int {
        return R.layout.activity_user_shared
    }

    override fun initViewModel() {
        userSharedViewModel = getActivityScopeViewModel(UserSharedViewModel::class.java)
        userSharedViewModel.squareRequest.userSharedResult.observe(this, Observer { t ->
            initDataResponse(t)
        })
        userSharedViewModel.squareRequest.mySharedResult.observe(this, Observer { t ->
            initDataResponse(t)
        })
        initAddCollectArticle()
        initDelCollectArticle()
        initDeleteShared()
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {
        ARouter.getInstance().inject(this)
        iv_back.setOnClickListener { finish() }

        if (userId == 0 || userId == -1) {
            tv_title.text = "我的分享"
            tv_right.text = "分享"
            tv_right.visibility = View.VISIBLE
            tv_right.setOnClickListener {
                ARouter.getInstance().build(ARouterPath.SHARE_ARTICLE).navigation(this, 100)
            }
        } else {
            tv_title.text = nickName + "的分享"
        }

        refresh_layout!!.setRefreshHeader(ClassicsHeader(this))

        //头部banner
        val view = View.inflate(this, R.layout.list_user_shared_header, null)
        tvUserName = view.findViewById(R.id.tv_userName)
        tvCoins = view.findViewById(R.id.tv_coins)
        tvLevel = view.findViewById(R.id.tv_level)

        tvUserName.text = if (userId == 0 || userId == -1) {
            MMKVUtils.getString(Constants.USERNAME_CACHE_KEY)
        } else {
            nickName
        }

        articleAdapter = ArticleAdapter(R.layout.item_article, null)
        articleAdapter.addHeaderView(view)
        articleAdapter.loadMoreModule.loadMoreView = SimpleLoadMoreView()

        recycler_view!!.layoutManager = LinearLayoutManager(this)
        recycler_view!!.adapter = articleAdapter

        articleAdapter.loadMoreModule.setOnLoadMoreListener {
            //加载更多
            index++
            getData()
        }
        refresh_layout!!.setOnRefreshListener {
            //刷新数据
            index = 1
            getData()
        }
        articleAdapter.setOnItemClickListener { _, _, position ->
            //文章点击
            val articleBean = articleAdapter.getItem(position)
            startToWeb(articleBean.link, articleBean.title)
        }
        articleAdapter.addChildClickViewIds(R.id.view_collect)
        articleAdapter.setOnItemChildClickListener { _, childView, position ->
            val articleBean = articleAdapter.getItem(position)
            if (childView.id == R.id.view_collect) {
                if (articleBean.collect) {
                    userSharedViewModel.requestDelCollectArticle(articleBean.id)
                } else {
                    userSharedViewModel.requestAddCollectArticle(articleBean.id)
                }
            }
        }
        articleAdapter.setOnItemLongClickListener { _, _, position ->
            val articleBean = articleAdapter.getItem(position)
            showOperationDialog(articleBean)
            return@setOnItemLongClickListener true

        }

        getData()
    }

    /**
     * 请求列表数据
     */
    private fun getData() {
        if (userId == 0 || userId == -1) {
            userSharedViewModel.requestMyShared(index)
        } else {
            userSharedViewModel.requestUserShared(userId, index)
        }
    }

    /**
     * 初始化数据请求回调
     */
    @SuppressLint("SetTextI18n")
    private fun initDataResponse(responseResult: ResponseResult<UserSharedBean>) {
        if (responseResult.errorCode == 0) {
            val userSharedBean = responseResult.data
            val coinInfo = userSharedBean!!.coinInfo
            tvUserName.text =
                if (!TextUtils.isEmpty(coinInfo.nickname)) coinInfo.nickname else coinInfo.username
            tvCoins.text = "积分：" + coinInfo.coinCount
            tvLevel.text = "等级：" + coinInfo.level


            if (userSharedBean.shareArticles.curPage == 1) {
                articleAdapter.setList(userSharedBean.shareArticles.datas)
            } else {
                articleAdapter.addData(userSharedBean.shareArticles.datas)
            }
            if (userSharedBean.shareArticles.curPage >= userSharedBean.shareArticles.pageCount) {
                articleAdapter.loadMoreModule.loadMoreEnd()
            } else {
                articleAdapter.loadMoreModule.loadMoreComplete()
            }
        } else {
            articleAdapter.loadMoreModule.loadMoreComplete()
        }
        refresh_layout!!.finishRefresh()
    }

    /**
     * 删除分享文章的接口回调
     */
    private fun initDeleteShared() {
        userSharedViewModel.squareRequest.deleteSharedResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                articleAdapter.let {
                    val list = it.data
                    for (i in list) {
                        if (t.data == i.id) {
                            list.remove(i)
                            break
                        }
                    }
                    it.notifyDataSetChanged()
                }
            }
        })
    }

    /**
     * 收藏文章接口回调
     */
    private fun initAddCollectArticle() {
        userSharedViewModel.collectRequest.addArticleResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                articleAdapter.let {
                    val list = it.data
                    for (i in list) {
                        if (t.data == i.id) {
                            i.collect = true
                        }
                    }
                    it.notifyDataSetChanged()
                }
            }
        })
    }

    /**
     * 取消收藏文章接口回调
     */
    private fun initDelCollectArticle() {
        userSharedViewModel.collectRequest.delArticleResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                articleAdapter.let {
                    val list = it.data
                    for (i in list) {
                        if (t.data == i.id) {
                            i.collect = false
                        }
                    }
                    it.notifyDataSetChanged()
                }
            }
        })
    }

    /**
     * 跳转到web页面
     */
    private fun startToWeb(linkUrl: String, title: String) {
        var url = linkUrl
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = Env.getDomain() + url
        }

        ARouter.getInstance().build(ARouterPath.WEB).withString("url", url)
            .withString("title", title).navigation()
    }

    /**
     * 显示操作弹窗
     */
    private fun showOperationDialog(articleBean: ArticleBean) {
        OperationDialog(this).apply {
            addSelectItems("打开链接", if (articleBean.collect) "取消收藏" else "收藏")
            if (userId == 0 || userId == -1) {
                addSelectItem("删除")
            }
            setOnSelectListener(object : OperationDialog.OnSelectListener {
                override fun onSelect(name: String, position: Int) {
                    if (position == 0) {
                        startToWeb(articleBean.link, articleBean.title)
                    } else if (position == 1) {
                        if (articleBean.collect) {
                            userSharedViewModel.requestDelCollectArticle(articleBean.id)
                        } else {
                            userSharedViewModel.requestAddCollectArticle(articleBean.id)
                        }
                    } else if (position == 2) {
                        userSharedViewModel.requestDeleteShared(articleBean.id)
                    }
                    dismiss()
                }
            })
        }.show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
            refresh_layout.autoRefresh()
        }
    }
}